<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>一个简易百度地图Demo</title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>
<style type="text/css">
body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;}
.container {height:100%;width:78%;float:left;border-right:2px solid #bcbcbc;}
.a_view {height:100%;width:20%;float:left;}
</style>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.json-2.2.min.js"></script>
<script type="text/javascript" src="js/hash.js"></script>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script>

<body>

<!-- 此处展示地图视图 -->
<div class="container" id="container"></div>

<!-- 此处存放对应标注的链接 -->
<div id="a_view" class="a_view">
	<!-- 此处修改坐标后的反馈消息 -->
	<div id="msg_view">&nbsp;</div><br/>
</div>

</body>


<!-- 开始加载地图的处理 -->
<script type="text/javascript">
// 存储信息窗的hash表
var infoWindowMap = new Hash(); 
// 存储标注的hash表
var markerMap = new Hash();	  

var buildingJsonStr = '[{"buildingId": "0710101842282A67E3162603F6250D67", "name": "02", "x": "31.22127", "y": "121.398516"}, {"buildingId": "07101018422820AD64EAB3AC576FFD3E", "name": "03", "x": "31.221587", "y": "121.397745"}, {"buildingId": "07101018422845B31172C77A176BDB43", "name": "04", "x": "31.220695", "y": "121.39827"}, {"buildingId": "071010184228A7EF4B0094030694C1B5", "name": "05", "x": "31.220769", "y": "121.397956"}, {"buildingId": "071010184228057205C5220A4924B99F", "name": "06", "x": "31.220178", "y": "121.398149"}, {"buildingId": "07101018422891C6FB5F3838EA67AEB6", "name": "07", "x": "31.220236", "y": "121.397776"}, {"buildingId": "071010184228E99A96B62460853A93B0", "name": "08", "x": "31.220576", "y": "121.397269"}, {"buildingId": "071010184228F4A035D852D89F418667", "name": "09", "x": "31.220638", "y": "121.396932"}, {"buildingId": "071010184228869C8C3AA796DB2D6A17", "name": "10", "x": "31.22051", "y": "121.39633"}, {"buildingId": "0710101842288CD20D0E333F3D775AEE", "name": "11", "x": "31.220634", "y": "121.395917"}, {"buildingId": "071010184228465B808DF2361EF74872", "name": "12", "x": "31.221186", "y": "121.396132"}, {"buildingId": "07101018422876B9BD4DD764214A37EF", "name": "13", "x": "31.221151", "y": "121.396478"}, {"buildingId": "07101018422860A7AEE993AD2F3D254E", "name": "14", "x": "31.221923", "y": "121.396478"}, {"buildingId": "071010184228D993F7D6F104C6241EA0", "name": "15", "x": "31.221529", "y": "121.397035"}, {"buildingId": "071010184228C77408F277C2A0FFF9EA", "name": "16", "x": "31.222487", "y": "121.39682"}, {"buildingId": "07101018422850C5CEFCC37B745AE217", "name": "17", "x": "31.222155", "y": "121.397278"}, {"buildingId": "071010184228CE5998B16072B7EADAF0", "name": "18", "x": "31.222992", "y": "121.396829"}, {"buildingId": "071010184228C4AE0885ED1B1934CAC7", "name": "19", "x": "31.223008", "y": "121.397215"}, {"buildingId": "071010184228A28019A162C9F30FB412", "name": "20", "x": "31.223054", "y": "121.397745"}, {"buildingId": "071010184228BE86B8C490400D07A7D9", "name": "21", "x": "31.223039", "y": "121.398109"}, {"buildingId": "0710101842284F721F26E60E4AE38B78", "name": "22", "x": "31.223062", "y": "121.398702"}, {"buildingId": "07101018422835C890FA62A7AC3D7B4F", "name": "23", "x": "31.223077", "y": "121.399106"}, {"buildingId": "0710101842293A343A9B0EE1A2F87ED6", "name": "24", "x": "31.222533", "y": "121.398567"}, {"buildingId": "0710101842298447B5294F823BF14B2E", "name": "25", "x": "31.222128", "y": "121.398109"}, {"buildingId": "07101018422905330D8B854F88DD30DD", "name": "26", "x": "31.221888", "y": "121.398769"}]';

var estateJsonStr = '[{"estateId": "0705280229021824977FE8318D179397", "name": "天山河畔花园", "address": "水城路883弄/长宁路", "x": "31.221034", "y": "121.397223"}]'

/**
 * 获取相关的json数组
 * @returns
 */
function getJsonData() {
    var reltJson;
    var url = "Your url"; 

	// 此处注释请求后台程序获取json数组的方法，直接返回定义好的json数组
//    $.ajax({
//        type: 'GET',
//        url: url,
//        async: false,
//        dataType: 'json',
//        timeout: 50000,
//        cache: false,
//        error: function(XMLHttpRequest, status, thrownError) {
//            alert('Error loading ' + url +', Please send it again!');
//        },
//        success: function(json) {
//            reltJson = json;
//        }
//    });
	
	// 转换json数组字符串成json对象，正式使用时上述ajax方法直接拿到的是json对象，不需要这步操作
	reltJson = eval(buildingJsonStr);

    return reltJson;
}

// 全局变量
var map;			// 地图对象		
var estateJson;		// 中心点json数据
var mouseoutIcon;   // 鼠标移出标注时的图像对象
var mouseoverIcon;  // 鼠标放在标注时的图像对象

// 绘制地图
drawMap();

/**
 * 绘制地图
 */
function drawMap(){
	estateJson = eval(estateJsonStr)[0];															// 初始化中心点的json数据
	map = new BMap.Map("container",{mapType: BMAP_HYBRID_MAP, enableHighResolution: true});			// 设置卫星图为底图
	initIcon();
	configuration();
	buildContextMenu();
	initCenterMarker();
	initOtherMarkers();
}

/**
 * 地图基本功能设置
 * @param map
 */
function configuration(){
	// 初始化中心坐标
	var point = getPoint(estateJson.y, estateJson.x);				
	// 启用键盘操作
	map.enableKeyboard();								
	// 启用滚轮放大缩小
	map.enableScrollWheelZoom();		
	// 初始化地图,设置中心点坐标和地图级别
	map.centerAndZoom(point, 18);                    			
	// 添加比例尺控件
	map.addControl(new BMap.ScaleControl());		
	// 添加平移缩放控件
	map.addControl(new BMap.NavigationControl());											
	// 启用地图惯性拖拽
	map.enableInertialDragging();										
	// 展示普通街道、卫星和路网的混合视图
	map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]}));	
	// 创建缩略地图控件
	var control = new BMap.OverviewMapControl();										
	// 展开缩略地图控件，默认不展开
	control.changeView();		
	// 添加缩略地图控件
	map.addControl(control);  
	// 设置地图显示的城市 此项是必须设置的
	map.setCurrentCity("上海");          															
}

/**
 * 创建右键菜单
 */
function buildContextMenu(){
	var contextMenu  = new BMap.ContextMenu();
	var txtMenuItem = [
	  {
	   text:'放大',
	   callback:function(){map.zoomIn();}
	  },
	  {
	   text:'缩小',
	   callback:function(){map.zoomOut();}
	  },
	  {
	   text:'放置到最大级',
	   callback:function(){map.setZoom(20);}
	  }
	 ];

	for(var i=0; i < txtMenuItem.length; i++){
		contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100));
		if(i==1 || i==3) {
			contextMenu.addSeparator();
		}
	}
	map.addContextMenu(contextMenu);
}

/**
 * 初始化标注图像
 */
function initIcon(){
	mouseoutIcon = new BMap.Icon("images/marker-icon.gif", new BMap.Size(12, 21), {imageOffset:new BMap.Size(-46,0)});
	mouseoverIcon = new BMap.Icon("images/marker-icon.gif", new BMap.Size(12, 21), {imageOffset:new BMap.Size(-69,0)});
}

/**
 * 初始化中心点标注
 */
function initCenterMarker(){
	addMarker(getPoint(estateJson.y, estateJson.x), estateJson.name, estateJson.estateId)
}

/**
 * 初始化其他标注
 */
function initOtherMarkers(){
	// 获取其他json数据
	var markersJson = getJsonData();
	$.each(markersJson, function(){
		addMarker(getPoint(this.y, this.x), this.name, this.buildingId);
	});
}


/**
 * 获取栋座坐标point对象
 * 无坐标时，随机生成在小区坐标附近
 * @param y
 * @param x
 */
function getPoint(y, x){
	// 因为json字符串中定义的是字符串，需要转换成float
	var _y = parseFloat(y);
	var _x = parseFloat(x);
	
	// 如果是有效的坐标，则直接创建point
	if(_y > 0 || _x > 0)
		return new BMap.Point(_y, _x);
	
	// 如果不是有效坐标，则创建中心点附近的随机坐标值
	var bounds = map.getBounds();
	var sw = bounds.getSouthWest();
	var ne = bounds.getNorthEast();
	var lngSpan = Math.abs(sw.lng - ne.lng);
	var latSpan = Math.abs(ne.lat - sw.lat);
	return new BMap.Point(sw.lng + lngSpan * (Math.random() * 0.8), ne.lat - latSpan * (Math.random() * 0.8));
}

/**
 * 添加多个标注
 * @param point 坐标
 * @param text 标注文本
 * @param buildingId 编号
 */
function addMarker(point, text, id){
	// 创建标注
	var marker = new BMap.Marker(point, {icon:mouseoutIcon});
	marker.setLabel(new BMap.Label(text, {offset:new BMap.Size(9,-20)}));
	marker.setTitle(text);
	marker.enableDragging();
	
	// 标注拖拽结束后绑定的事件
	marker.addEventListener("dragend", function(e){
		editCoord(id, e.point.lat, e.point.lng, text);
	});
	
	// 鼠标离开标注时绑定的事件
	marker.addEventListener("mouseout", function(e){
		marker.setIcon(mouseoutIcon);
	});

	// 鼠标移到标注时绑定的事件
	marker.addEventListener("mouseover", function(e){
		marker.setIcon(mouseoverIcon);
	});

	// 鼠标点击标注时绑定的事件
	marker.addEventListener("click", function(e){ 
		marker.openInfoWindow(infoWindow);
	});
	
	// 信息窗关闭时绑定的事件
	marker.addEventListener("infowindowclose", function(e){ 
		marker.setIcon(mouseoutIcon);
	});

	// 信息窗打开时绑定的事件
	marker.addEventListener("infowindowopen", function(e){ 
		marker.setIcon(mouseoverIcon);
	});
	 
	// 显示到地图中
	map.addOverlay(marker);

	//创建信息窗
	var infoWindow = new BMap.InfoWindow(getContent(text));	

	// 存储到hash
	infoWindowMap.put(id, infoWindow);
	markerMap.put(id, marker);

	var link = '<li><a href="javascript:void(0);" onclick="showInfoWindos(\''+id+'\')">'+ text +'</a></li>';
	$('#a_view').append(link);
}

/**
 * 展示标注的信息窗
 * @param id
 */
function showInfoWindos(id){
	var marker = markerMap.get(id);
	if(infoWindowMap.get(id) != undefined){
		marker.openInfoWindow(infoWindowMap.get(id));
	}
}



/**
 * 保存坐标编辑
 * @param id
 * @param x
 * @param y
 * @param name
 */
function editCoord(id, x, y, name){
//    $.ajax({
//        type: 'POST',
//        url: 'Your url',
//        data: {	
//				'id' : id, 
//				'x' : x, 
//				'y' : y
//		},
//        success: function(data) {
//            showMsg("<strong>" + name + "修改后的坐标已自动保存</strong>");
//        }
//    });

	showMsg('<strong>"' + name + '"修改后的坐标已自动保存</strong>');
}

/**
 * 获取信息窗html
 */
function getContent(name){
	var content = "<div><p>{name}</p></div>";
	return content.replace("{name}", name);
}

/**
 * 展示坐标修改后的提醒内容
 */
function showMsg(msg){
	$('#msg_view').html(msg);
}


</script>
</html>
